package com.csproj.dispatch.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import liquibase.util.StringUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ZonedDateTime json时间格式化
 */
public class DateJsonDeserializer extends JsonDeserializer<ZonedDateTime> {
    public static final DateTimeFormatter beijingFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter beijingFormatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    @Override
    public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String eL = "[0-9]{4}-[0-9]{2}-[0-9]{2}";//匹配yyyy-MM-dd
        Pattern p = Pattern.compile(eL);
        try
        {
            if(jsonParser!=null&&StringUtils.isNotEmpty(jsonParser.getText())){
                Matcher m = p.matcher(jsonParser.getText());
                if (m.matches()){
                    return LocalDate.parse(jsonParser.getText(), beijingFormatter).atStartOfDay().atZone(ZoneId.of("Asia/Shanghai"));
                }
                return LocalDate.parse(jsonParser.getText(), beijingFormatters).atStartOfDay().atZone(ZoneId.of("Asia/Shanghai"));
            }else {
                return null;
            }

        }
        catch(Exception e)
        {
            throw new RuntimeException(e);
        }

    }
}
